package com.tk.exam.web.admin;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.tk.exam.domain.TkOperator;
import com.tk.exam.domain.TkToken;
import com.tk.exam.exception.ApiException;
import com.tk.exam.http.Response;
import com.tk.exam.interceptor.NoCheckHttpHeader;
import com.tk.exam.service.TkOperatorServer;
import com.tk.exam.service.TkTokenService;
import com.tk.exam.utils.DESUtil;
import com.tk.exam.utils.SSOUtil;
import com.tk.exam.utils.TokenThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("tk/exam/admin")
@Slf4j
public class AdminController {


    @Autowired
    TkTokenService tkTokenService;
    @Autowired
    TkOperatorServer tkOperatorServer;
    @Autowired
    SSOUtil ssoUtil;


    @PostMapping("/login")
    @NoCheckHttpHeader
    public Response login(@RequestBody Map<String, String> params) {
        if (params == null || params.size() == 0) {
            throw ApiException.of("用户名或密码不能为空");
        }
        String username = params.get("username");
        String password = params.get("password");

        //参数校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
           throw ApiException.of("用户名或密码不能为空");
        }
        //校验密码
        password = DESUtil.getEncryptPassword(password);
        TkOperator tkOperator = tkOperatorServer.getByLoginName(username);
        if (Objects.isNull(tkOperator)||!password.equals(tkOperator.getOpePassword())) {
            throw ApiException.of("用户名或密码错误");
        }
        //保存token
        Map tokenInfoMap = new HashMap();
        tokenInfoMap.put("loginType", "admin");
        tokenInfoMap.put("userId", tkOperator.getId());
        tokenInfoMap.put("username", tkOperator.getOpePhone());
        tokenInfoMap.put("password", tkOperator.getOpePassword());
        tokenInfoMap.put("opeName", tkOperator.getOpeName());
        String tokenInfo = JSON.toJSONString(tokenInfoMap);
        TkToken tkToken = ssoUtil.generateToken(tokenInfo);
        tkTokenService.saveToken(tkToken);
        //返回json
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("token", tkToken.getToken());
        data.put("username", tkOperator.getOpeName());
        data.put("phone", tkOperator.getOpePhone());
        return Response.succeed(data);
    }

    @PostMapping("/logout")
    public Response logout() {
        TkToken tkToken = TokenThreadUtil.getTkToken();
        tkTokenService.removeToken(tkToken);
        return Response.succeed();
    }

}
